package com.swedne.test.net;


import android.content.Context;
import android.net.EthernetManager;
import android.net.IpConfiguration;
import android.net.IpConfiguration.IpAssignment;
import android.net.IpConfiguration.ProxySettings;
import android.net.StaticIpConfiguration;
import android.net.LinkAddress;
import android.net.NetworkUtils;
import android.os.Build;


import androidx.annotation.RequiresApi;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.Inet4Address;
import java.net.InetAddress;

public class Ethernet {
    public static int dhcp = 0;
    public static String ip = "192.168.14.170";
    public static String mask = "255.255.255.0";
    public static String gateway = "192.168.14.1";
    public static String dns = "8.8.8.8";


    public static EthernetManager mEthManager = null;


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static boolean configure(Context context) {
        mEthManager = (EthernetManager)context.getSystemService("ethernet");
        boolean ok = false;
        if (dhcp == 0) {
            try {
                StaticIpConfiguration sIp = new StaticIpConfiguration();
                int m = NetworkUtils.netmaskToPrefixLength((Inet4Address) NetworkUtils.numericToInetAddress(mask));
                String address = ip + "/" + String.valueOf(m);
//                sIp.ipAddress = new LinkAddress(address);
                Constructor<?> laConstructor = LinkAddress.class.getConstructor(String.class);
                sIp.ipAddress = (LinkAddress) laConstructor.newInstance(address);
                sIp.gateway = (Inet4Address) NetworkUtils.numericToInetAddress(gateway);
                sIp.dnsServers.add((Inet4Address) NetworkUtils.numericToInetAddress(dns));
                IpConfiguration c = new IpConfiguration(IpAssignment.STATIC, ProxySettings.NONE, sIp, null);
                mEthManager.setConfiguration("eth0", c);
                ok = true;
            } catch (java.lang.IllegalArgumentException e) {
                e.printStackTrace();
            } catch (java.lang.RuntimeException e2) {
                e2.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } else {
            ok = true;
            mEthManager.setConfiguration("eth0", new IpConfiguration(IpAssignment.DHCP, ProxySettings.NONE, null, null));
        }
        return ok;
    }
}
